<?php

namespace App\Models;

use App\Models\Game\Server;
use App\Utils\MyLog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;

class DynamicConnectionModel extends Model
{
    public function __construct(array $attributes = [])
    {
        $this->setDatabaseConnection();
        parent::__construct($attributes);
    }

    protected function setDatabaseConnection()
    {
        global $datakey;
        global $gameArea;

        $serverConfig = $this->getServerConfig();
        MyLog::info('动态数据库连接词:'.json_encode($serverConfig));
        MyLog::info('$datakey词:'.json_encode($datakey));

        if ($serverConfig) {
            Config::set('database.connections.dynamic', [
                'driver'    => 'mysql',
                'host'      => $serverConfig->host,
                'port'      => $serverConfig->port,
                'database'  => $datakey,
                'username'  => $serverConfig->username,
                'password'  => $serverConfig->password,
                'charset'   => 'utf8mb4',
                'collation' => 'utf8mb4_unicode_ci',
                'prefix'    => '',
                'strict'    => true,
            ]);
        MyLog::info('当前选择的数据库连接参数:'.json_encode(Config::get('database.connections.dynamic')));
            $this->setConnection('dynamic');
        } else {
            // 如果没有找到服务器配置,使用默认数据库连接

            $this->setConnection('game_'.$gameArea);
            //$this->setConnection(Config::get('database.default'));
        }
    }

    protected function getServerConfig()
    {
        global $gameArea;

        if ($gameArea) {
            return Server::where('server_id', $gameArea)
                ->first();
        }

        return null;
    }
}


